import { CHUNK_SIZE } from '../../../utils/createFileChunk';

export default function useFileCutter() {
    // 最大线程数量
    const MAX_THREAD_COUNT = navigator.hardwareConcurrency || 4

    // 文件分片
    const cutFile = async function (file, chunkSize = CHUNK_SIZE) {
        return new Promise(resolve => {
            // 线程数量、文件块数量
            const chunkCount = Math.ceil(file.size / chunkSize);
            const threadCount = Math.min(MAX_THREAD_COUNT, chunkCount);
            // 单个线程需要处理的文件块数量
            const chunkCountPerThread = Math.ceil(chunkCount / threadCount);
            // 记录结果
            const result = [];
            let finishedCount = 0;
            for (let i = 0; i < threadCount; i++) {
                // 单个线程需要处理的文件块范围
                const start = i * chunkCountPerThread;
                const end = Math.min(start + chunkCountPerThread, chunkCount);
                // 创建线程
                const worker = new Worker('/src/workers/createFileChunkWorker.js', { type: 'module' });
                // 发送文件处理相关信息
                worker.postMessage({ file, chunkSize, startChunkIndex: start, endChunkIndex: end });
                // 接收处理结果
                worker.onmessage = e => {
                    for (let i = start; i < end; i++) {
                        result[i] = e.data[i - start];
                    }
                    // 结束线程并记录
                    worker.terminate();
                    if (++finishedCount === threadCount) resolve(result);
                };
            }
        });
    };

    return { cutFile };
};